//使用verilog 完成一个串口接收数据模块
module uart_rx(
    input  wire        clk,
    input  wire        rst,
    input  wire        rx,
    output wire        data_valid,
    output wire [7:0]  data
);
    reg [7:0]  rx_data;
    reg        rx_start;
    reg        rx_done;
    reg        rx_error;

    always @(posedge clk or negedge rst) begin
        if (!rst) begin
            rx_start <= 0;
            rx_done  <= 0;
            rx_error <= 0;
        end else begin
            if (rx_start) begin
                if (rx_done) begin
                    rx_start <= 0;
                    rx_done  <= 0;
                    rx_error <= 0;
                end else if (rx_error) begin
                    rx_start <= 0;
                    rx_done  <= 1;
                    rx_error <= 0;
                end else if (rx) begin
                    rx_data  <= {rx_data[6:0], rx};
                    if (rx_data == 8'hFF) begin
                        rx_done  <= 1;
                        rx_error <= 0;
                    end
                end
            end else if (rx) begin
                rx_start <= 1;
                rx_data  <= {rx, 7'b0};
            end
        end
    end

    assign data_valid = rx_done;
    assign data       = rx_data;
endmodule   